package com.yao.system.aspect;


import com.yao.system.annotation.MyLimit;
import com.yao.system.util.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Component
@Aspect
@Slf4j
@RequiredArgsConstructor
public class MyLimitAspect {

    private final StringRedisTemplate redisTemplate;

    @Pointcut("@annotation(com.yao.system.annotation.MyLimit)")
    public void pointcut() {
    }

    @Around(("@annotation(limit)"))
    public Object limitRequest(ProceedingJoinPoint joinPoint, MyLimit limit) throws Throwable {
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        Signature signature = joinPoint.getSignature();
        String methodName = signature.getName();

        //开始限流判断
        log.info("=========开始对该接口进行限流判断:接口 {}============",methodName);
        StringBuffer url = request.getRequestURL();
        log.info("======请求URL : {}", url);
        String method = request.getMethod();
        log.info("===========请求方法:{}", method);
        log.info("=======全路径及执行方法:{},{}", signature.getDeclaringTypeName(), methodName);
        log.info("========  IP : {}", request.getRemoteHost());

        LocalDateTime now = LocalDateTime.now();
        long maxTime = now.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        LocalDateTime minutes = now.minusMinutes(limit.time());
        long minTime = minutes.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        String key = limit.name() + UserContext.getUser().getId();
        Long requestCount = redisTemplate.opsForZSet().count(key, minTime, maxTime);
        if (requestCount != null && requestCount >= limit.value()) {
            log.info("=========请求数量已超出，进行限流处理=========");
            return null;
        }
        log.info("=====当前请求限流通过====");
        redisTemplate.opsForZSet().add(key, String.valueOf(maxTime), maxTime);
        //log.info("===== 请求入参:{}", JSONUtil.toJsonStr(joinPoint.getArgs()));
        //log.info("============================================================");
        return joinPoint.proceed();
    }


    //@Before("pointcut()")
    //public void beforeLog(JoinPoint joinPoint) {
    //    ServletRequestAttributes requestAttributes =
    //            (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    //    HttpServletRequest request = requestAttributes.getRequest();
    //    Signature signature = joinPoint.getSignature();
    //    String methodName = signature.getName();
    //
    //    log.info("============================== 接口名：{} ====================", methodName);
    //    StringBuffer url = request.getRequestURL();
    //    log.info("======请求URL : {}", url);
    //    String method = request.getMethod();
    //    log.info("===========请求方法:{}", method);
    //    log.info("=======全路径及执行方法:{},{}", signature.getDeclaringTypeName(), methodName);
    //    log.info("========  IP   : {}", request.getRemoteHost());
    //    log.info("===== 请求入参:{}", JSONUtil.toJsonStr(joinPoint.getArgs()));
    //    log.info("============================================================");
    //
    //}
    //
    //@After("pointcut()")
    //public void afterLog(JoinPoint joinPoint) {
    //    ServletRequestAttributes requestAttributes =
    //            (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    //    HttpServletRequest request = requestAttributes.getRequest();
    //    Signature signature = joinPoint.getSignature();
    //    String methodName = signature.getName();
    //
    //    log.info("============================== 接口：{} 执行完成 ====================", methodName);
    //
    //}

}

